import { useSocketStore } from '../stores/socket'

// 统一的事件常量，供各处订阅使用
// 注：字符串需与后端推送的事件名一致，如有差异可在此集中调整
export const GAME_EVENTS = {
  ROOM_JOINED: 'RoomJoined',
  PLAYER_JOINED: 'PlayerJoined',
  GAME_STARTED: 'GameStarted',
  // 统一成自定义别名，便于前端多处使用
  DRAWING_MOVE: 'PaintAction',
  CANVAS_CLEARED: 'CanvasCleared',
  GAME_ENDED: 'GameEnded'
}

// 对 Pinia 的 socket store 做一层轻管理封装
// 目的：
// - 暴露 Promise 风格方法以兼容既有调用（.then/.catch）
// - 统一入口，便于后续替换实现
const socketManager = {
  async connect(/* accessToken */) {
    // 连接时 accessToken 由 store 内部通过 accessTokenFactory 从 localStorage 读取
    const store = useSocketStore()
    await store.connect()
    return true
  },

  disconnect() {
    const store = useSocketStore()
    return store.disconnect()
  },

  reconnect() {
    const store = useSocketStore()
    return store.reconnect()
  },

  getConnectionStatus() {
    const store = useSocketStore()
    // 直接调用store的getConnectionStatus方法
    return store.getConnectionStatus()
  },

  on(event, callback) {
    const store = useSocketStore()
    store.on(event, callback)
  },

  off(event, callback) {
    const store = useSocketStore()
    store.off(event, callback)
  },

  once(event, callback) {
    const store = useSocketStore()
    store.once(event, callback)
  },

  // 业务方法 - 统一返回 Promise 以兼容调用端的 .catch()
  async createRoom(data) {
    const store = useSocketStore()
    store.createRoom(data)
    return true
  },

  async joinRoom(roomId, playerName) {
    const store = useSocketStore()
    // 与后端约定：JoinRoom 参数对象
    const ok = await store.joinRoom({ roomId, playerName })
    return !!ok
  },

  async leaveRoom(roomId) {
    const store = useSocketStore()
    store.leaveRoom(roomId)
    return true
  },

  async startGame(roomId) {
    const store = useSocketStore()
    await store.startGame(roomId)
    return true
  },

  // 玩家准备状态（与 store 对齐）
  async playerReady(payload) {
    // payload: { roomId, playerId, isReady }
    const store = useSocketStore()
    await store.playerReady(payload)
    return true
  },

  // 便捷方法：按房间ID设置当前用户是否准备
  async setPlayerReady(roomId, isReady) {
    const store = useSocketStore()
    return store.setPlayerReady(roomId, isReady)
  },

  async paintAction(paintData) {
    const store = useSocketStore()
    // 立即发送绘画动作，减少延迟
    store.paintAction(paintData)
    return true
  },

  async resetCanvas(roomId) {
    const store = useSocketStore()
    store.resetCanvas(roomId)
    return true
  },

  async gameResult(resultData) {
    const store = useSocketStore()
    store.gameResult(resultData)
    return true
  }
}

export default socketManager


